package ee.subjects.frontend.controller.command.enterpriseCommands;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ee.subjects.backend.model.data.Enterprise;
import ee.subjects.backend.services.EnterpriseService;
import ee.subjects.backend.services.EnterpriseServiceImpl;
import ee.subjects.frontend.controller.command.Command;

public class AllEnterprisesCommand implements Command {

	@Override
	public int execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// If task to delete
		if(request.getParameter("task")!=null){
			this.finishTask(request);
		}

		EnterpriseService enterpriseService = new EnterpriseServiceImpl();
		List<Enterprise> allEnterprise = enterpriseService.getAllEnterprises();
		
		request.setAttribute ("AllEnterprises", allEnterprise);

		return 0;
	}

	private void finishTask(HttpServletRequest request) {
		if(request.getParameter("task").equals("delete")){
			int enterpriseToDelete = Integer.parseInt(request.getParameter("id"));
			
			EnterpriseService enterpriseService = new EnterpriseServiceImpl();
			enterpriseService.deleteEnterpriseAndItsRelatedData(enterpriseToDelete);
		}
		
	}

}
